from datetime import datetime

from waitress import serve
from apps.settingApi.api.timerTask.task import add_task
from comm.openDbConfig import openDbBase
from comm.secretKey import jieMi
from manage import app
import multiprocessing


from msgTkinter import msgTkinterClass
# from socketIo.main import start

dbproconfig = openDbBase()
def get_max_threads():
    """
    获取服务器核数用于开启最大线程
    :return:
    """
    try:
        num_cores = multiprocessing.cpu_count()
        max_threads = 2 * num_cores
    except Exception as e:
        return 4
    return max_threads



# def is_port_in_use(port):
#     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
#         try:
#             s.bind(('0.0.0.0', port))
#             return False
#         except OSError:
#             return True

def sratTornado():
    print('启动flask')
    try:
        serve(app, host='0.0.0.0', port=dbproconfig['CHARTPORT'], threads=get_max_threads())
    except Exception as e:
        print('启动失败')
        raise  ValueError("启动失败"+repr(e))
def startSocketio():
    print('启动socketio')
    # start()
def sratMsg():
    msgTkinterClass().a001()
def starTIme():
    add_task(trigger='interval', seconds=dbproconfig['TIME'])
# 启动定时任务
if __name__ == '__main__':
    # # 启动服务
    # sratTornado()
    # 创建两个进程
    # 格式化当前日期为 YYYY-MM-DD 格式
    # 获取当前日期
    # _,err = jieMi(dbproconfig['privateKey'])
    # if err!=None:
    #     raise ValueError(err)
    multiprocessing.freeze_support()
    multiprocessing.Process()
    multiprocessing.set_start_method('spawn')
    process1 = multiprocessing.Process(target=starTIme)
    process2 = multiprocessing.Process(target=sratTornado)

    # 启动进程
    process1.start()
    process2.start()

    # 等待所有进程完成
    process1.join()
    process2.join()
    # multiprocessing.freeze_support()
    # task_process = multiprocessing.Process(target=starTIme)
    # task_process.daemon = True
    # task_process.start()
    # task_process.join()
    # sratTornado()
